package cn.datax.service.data.market.mapping.controller;

import cn.datax.commo.office.excel.ExcelUtils;
import cn.datax.common.base.BaseController;
import cn.datax.common.core.R;
import cn.datax.common.database.core.PageResult;

import cn.datax.service.data.market.mapping.service.impl.ApiMappingEngine;
import cn.datax.service.data.market.table.entity.DataTableEntity;
import cn.datax.service.data.market.table.feign.DataTableServiceFeign;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * api调用日志信息表 前端控制器
 * </p>
 *
 * @author yuwei
 * @since 2020-08-21
 */
@Api(tags = {"table资源表"})
@RestController
@RequestMapping("/apiTable")
public class ApiDataController extends BaseController {

    @Autowired
    private ApiMappingEngine apiMappingEngine;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DataTableServiceFeign dataTableServiceFeign;

    /**
     * 通过ID查询信息
     *
     * @param id
     * @return
     */
    /**
     * 导出指定资源数据
     */
    @GetMapping("/export/tableData")
    public void exportFile(@PathVariable String id, HttpServletResponse response){
        try {
            DataTableEntity entity = dataTableServiceFeign.getDataResourceById(id);
            PageResult<Map<String, Object>> value = apiMappingEngine.getTableData(entity,new HashMap<>());
            List list = value.getData();
            List<Map<String, Object>> dtoList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                Map dto = new HashMap();
                try {
                    BeanUtils.copyProperties(dto,list.get(i));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                dtoList.add(dto);
            }
            ExcelUtils.exportExcel(dtoList,Map.class,"资源下载",response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
